import { Body, Controller, Ip, Post, Req } from '@nestjs/common';
import { CommonDto } from './dto/common';
import { LoginService } from './login.service';
import { ResponseUtilService } from '@app/response-util';
import { DtoPipe } from 'apps/admin/src/pipe/dto/dto.pipe';
import ChangePassword from './dto/changePassword.dto';
import { ReqAttrs } from 'apps/admin/src/constant';

@Controller('login')
export class LoginController {
    constructor(
        private readonly service:LoginService
    ) {}

    @Post('init')
    public async init(@Body(new DtoPipe()) dto:ChangePassword, @Ip() ip:string) {
        try {
            const r = await this.service.init(dto)

            return ResponseUtilService.successRes(r)

        } catch (error) {
            
            return ResponseUtilService.failRes(error.message, {code : error.code, data : error.count})
        }
    }

    @Post()
    public async login(@Body(new DtoPipe()) dto:CommonDto, @Ip() ip:string) {
        try {
            const r = await this.service.login(dto.account, dto.password, ip)

            return r ? ResponseUtilService.successRes(r) : ResponseUtilService.failRes()

        } catch (error) {
            
            return ResponseUtilService.failRes(error.message, {code : error.code, data : error.count})
        }
    }


    @Post('refresh')
    public async refresh(@Req() req) {
        try {
            const r = await this.service.refresh(req[ReqAttrs.MEMBER_ID])

            return ResponseUtilService.successRes(r)

        } catch (error) {
            
            return ResponseUtilService.failRes(error.message, {code : error.code, data : error.count})
        }
    }
}
